var express = require("express");
var router = express.Router();
var { Order } = require("../db/rili");
// 获取首页数据
router.get("/orders/:date", async (req, res) => {
  // const order = await Order.findOne({ date: req.params.date });
  // res.json(order || { orders: [] });

  const order = await Order.findOne({ date: req.params.date });
  res.json(order || { orders: [] });
});

router.get("/api/orders", async (req, res) => {
  try {
    const orders = await Order.find();
    console.log(orders[0].orders[1]);

    res.json(orders);
  } catch (error) {
    res.status(500).json({ error: "Failed to fetch orders" });
  }
});

router.post("/api/orders/cancel", async (req, res) => {
  try {
    const { orderId } = req.body;
    console.log("Received orderId:", orderId);

    // 查找并更新订单状态
    const order = await Order.findOneAndUpdate(
      { "orders.id": orderId }, // 查找订单
      { $set: { "orders.$.status": "cancelled" } }, // 更新状态
      { new: true } // 返回更新后的文档
    );

    if (!order) {
      return res.status(404).json({ error: "Order not found" });
    }
    res.json(order); // 返回更新后的订单
  } catch (error) {
    console.error("Cancel error:", error);
    res.status(500).json({ error: "Failed to cancel order" });
  }
});

// 添加数据
router.post("/madd", async (req, res) => {
  const { date, orders } = req.body;
  Order.create({ date, orders }).then((data) => {
    res.send({
      code: 200,
      msg: "添加成功",
    });
  });
});

router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

module.exports = router;
